<?php
/**
 * Created by PhpStorm
 * User: lcz
 * Date: 2019/11/8
 * Time: 19:00
 * 创业大赛
 */

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Team;
use app\common\model\TeamMember;
use think\Db;

class Plan extends Api {
	
	/**
	 * 参与中的大赛
	 */
	public function index() {
		$row = Db::name('businessPlan')
			->where(['area' => $this->area])
            ->order(['id' => 'desc'])
			->find();
		
		if($row) {
			$teamNumber = Db::name('team')->where(['business_plan_id' => $row['id']])
				->field('sum(number) as sale_number, count(id) as team_number')
				->find();
			
			$date = strtotime(date('Y-m-d'));
			
			if($row['apply_time'] <= $date && $row['start_time'] > $date) {
				//报名中
				$status = 0;
			} else if($row['start_time'] <= $date && $row['end_time'] >= $date && $teamNumber['sale_number'] < $row['number']) {
				//活动进行中
				$status = 1;
			} else {
				//活动已结束
				$status = 2;
			}
			
			$row['status'] = $status;
			$team = Db::name('teamMember')
				->where(['business_plan_id' => $row['id'], 'user_id' => $this->auth->id, 'status' => TeamMember::STATUS_NORMAL])
				->field('team_id')
				->find();
			$row['team_id'] = $team ? $team['team_id'] : '';
		}
		
		$this->success('查询成功', $row);
	}
	
	/**
	 * 团队
	 */
	
	public function team() {
		$id = $this->request->post('id', '', 'intval');
		!$id && $this->error('参数错误');
		
		$order = ['t.create_time' => 'asc'];
		$status = $this->request->post('status');
		if($status && $status == 2) {
			$order = ['sale_number' => 'desc'];
		}
		
		
		
		$teams = Db::name('team')->alias('t')
			->join('user u', 't.user_id = u.id', 'left')
			->where(['t.business_plan_id' => $id])
			->field('t.id, t.name, t.number, u.nickname, t.member')
			->order($order)
			->select();
		
		$this->success('查询成功', $teams);
	}
	
	/**
	 * 创建团队
	 */
	public function createTeam(){
		$id = $this->request->post('id', '', 'intval');
		$name = $this->request->post('name');
		$data = $this->request->post();
		$validate = new \app\common\validate\Team();
		if(!$validate->check($data)) {
			$this->error($validate->getError());
		}
		
		$plan = Db::name('businessPlan')->find($id);
		!$plan && $this->error('活动不存在');
		
		if($plan['end_time'] < time()) {
			$this->error('活动已结束');
		}
		
		if($plan['start_time'] < time()) {
			$this->error('报名已结束');
		}
		
		if($plan['apply_time'] > time()) {
			$this->error('报名时间未到');
		}
		
		if($plan['team_number'] > 0) {
			$teamNumber = Db::name('team')->where(['business_plan_id' => $id])->count();
			if($teamNumber >= $plan['team_number']) {
				$this->error('报名战队数量已满');
			}
		}
		$userId = $this->auth->id;
		
		$userModel = new \app\admin\model\User();
		$levelList = [$userModel::LEVEL_PROMOTION, $userModel::LEVEL_WAREHOUSE, $userModel::LEVEL_SHOP];
		if($this->area == $userModel::AREA_SZ) {
			$levelList[] = $userModel::LEVEL_CENTER;
		}
		
		//没有资格参与大赛的直接是不参与
		if(!in_array($this->auth->level, $levelList)) {
			$this->error('代理才能参与此活动,是否立即开通代理?', [],2);
		}
		
		$team = Db::name('teamMember')->where(['business_plan_id' => $id, 'user_id' => $userId, 'status' => TeamMember::STATUS_NORMAL])->find();
		$team && $this->error('你已经有战队了');
		
		$row = Db::name('team')->where(['business_plan_id' => $id, 'name' => $name])->find();
		$row && $this->error('战队名称已存在');
		
		
		
		$model = new Team();
		$teamId = $model->createTeam($id, $name, $userId, $data['weixin_code'], $data['slogan'], $data['image'], $data['content']);
		if($teamId) {
			$this->success('创建成功', $teamId);
		} else {
			$this->error($model->getError());
		}
		
	}
	
	/**
	 * 加入团队
	 */
	public function joinTeam() {
		$planId = $this->request->post('plan_id', '', 'intval');
		!$planId && $this->error('参数错误');
		
		$teamId = $this->request->post('team_id', 0, 'intval');
		$plan = Db::name('businessPlan')->find($planId);
		!$plan && $this->error('活动不存在');
		
		if($plan['start_time'] < time()) {
			$this->error('报名已结束');
		}
		
		$userModel = new \app\admin\model\User();
		$levelList = [$userModel::LEVEL_PROMOTION, $userModel::LEVEL_WAREHOUSE, $userModel::LEVEL_SHOP];
		if($this->area == $userModel::AREA_SZ) {
			$levelList[] = $userModel::LEVEL_CENTER;
		}
		
		//没有资格参与大赛的直接是不参与
		if(!in_array($this->auth->level, $levelList)) {
			$this->error('代理才能参与此活动,是否立即开通代理?', [],2);
		}
		
		$userId = $this->auth->id;
		$row = Db::name('teamMember')->where(['business_plan_id' => $planId, 'user_id' => $userId, 'status' => TeamMember::STATUS_NORMAL])->find();
		$row && $this->error('你已经加入过战队了');
		
		if($teamId) {
			$team = Db::name('team')->where(['business_plan_id' => $planId, 'id' => $teamId])->find();
			!$team && $this->error('战队不存在');
			if($plan['team_member'] > 0 && $team['member'] >= $plan['team_member']) {
				$this->error('战队人数已满');
			}
			$oldRow = Db::name('teamMember')->where(['business_plan_id' => $planId, 'user_id' => $userId, 'team_id' => $team['id'], 'status' => TeamMember::STATUS_DEL])->find();
			if($oldRow) {
				$this->error('该战队限制你加入');
			}
		} else {
			$teamIds =Db::name('teamMember')->where(['business_plan_id' => $planId, 'user_id' => $userId, 'status' => TeamMember::STATUS_DEL])->column('team_id', 'id');
			$where['business_plan_id'] = $planId;
			if($plan['team_member'] > 0) {
				$where['member'] = ['lt', $plan['team_member']];
			}
			
			if($teamIds) {
				$where['id'] = ['not in', $teamIds];
			}
			
			$team = Db::name('team')->where($where)->order(['create_time' => 'desc'])->find();
			if(!$team) {
				$this->error('没有找到相关战队，请稍候重试');
			}
		}
		
		
		
		$model = new TeamMember();
		$res = $model->joinTeam($planId, $team['id'], $userId);
		if($res) {
			$this->success('加入成功', $team['id']);
		} else {
			$this->error($model->getError());
		}
	}
	
	
	/**
	 * 我的团队
	 */
	public function teamDetail() {
		$teamId = $this->request->post('team_id', '', 'intval');
		!$teamId && $this->error('参数错误');
		
		$team = Db::name('team')->alias('t')
			->join('businessPlan p', 't.business_plan_id = p.id', 'left')
			->where(['t.id' => $teamId])
			->field('t.*, p.apply_time, p.start_time, p.end_time')
			->find($teamId);
		!$team && $this->error('战队不存在');
		
		
		$date = strtotime(date('Y-m-d'));
		if($team['apply_time'] <= $date && $team['start_time'] > $date) {
			//报名中
			$status = 0;
		} else if($team['start_time'] <= $date && $team['end_time'] >= $date) {
			//活动进行中
			$status = 1;
		} else {
			//活动已结束
			$status = 2;
		}
		
		$team['status'] = $status;
		
		$team['members'] = Db::name('teamMember')->alias('m')
			->join('user u', 'm.user_id = u.id', 'left')
			->where(['m.team_id' => $teamId, 'm.status' => TeamMember::STATUS_NORMAL])
			->field('m.id, u.nickname, m.number, m.user_id')
			->order(['create_time' => 'desc'])
			->select();
		$this->success('查询成功', $team);
	}
	
	/**
	 * 删除成员
	 */
	public function delMember(){
		$id = $this->request->post('id');
		$teamId = $this->request->post('team_id');
		(!$id || !$teamId) && $this->error('参数错误');
		
		$team = Team::get($teamId);
		if($team['user_id'] != $this->auth->id) {
			$this->error('不是你的团队');
		}
	
		$res = Db::name('teamMember')
			->where(['id' => $id, 'team_id' => $teamId])
			->update(['status' => TeamMember::STATUS_DEL]);
		
		Db::name('team')->where(['id' => $teamId])->setDec('member');
		
		if($res) {
			$this->success('删除成功');
		} else {
			$this->error('删除出错');
		}
		
	}
}